#!/usr/bin/python
import socket, cards, sys, threading, wx, disp, time, Queue

_HOST = 'localhost'
_PORT = 5555

class Client:
	def __init__(self, name, qin, qout, qmove, qstatus): 
		self.sock = socket.socket()
		self.name = name
		self.hand = []
		self.qIn = qin
		self.qOut = qout
		self.qMove = qmove
		self.qStatus = qstatus
		self.moveMade = None
		#self.thread = threading.Thread(target=self._waitForConnect)
		#self.thread.daemon = True
		#self.thread.start()
		#self._initGUI()
	
	def _initGUI(self):
		self.app = wx.App()
		self.frame = disp.Frame(self.qOut, self.qIn, self.qMove, self.qStatus, self.name)
		self.frame.Show()
		self.app.MainLoop()
		
	def _waitForConnect(self):
		while(True):
			while(self.qIn.qsize()):
				msg = self.qIn.get(0)
				if(msg == "conn"):
					self.connect()
					return 
				
	def connect(self):
		host = _HOST
		port = _PORT
		self.sock.connect((host, port))
		self.sock.send(self.name)
		resp = self.sock.recv(7)
		print resp
		seat = self._getSeat(resp)
		print seat
		self.sock.send(seat)
		resp = self.sock.recv(32)
		print "resp = " + resp
		pNum = resp[0]
		self.qMove.put("p" + pNum)
		resp = resp[1:]
		print resp
		self.qStatus.put("sWaiting for other players...")
		while(True):
			self.hand = cards.Hand()
			self._playGame()
	
	def _getHand(self):
		return self.hand.getHandList(":")
		
	def _getInput(self):
		card = self.frame.getInput()
		return card
		
	def _getRung(self):
		ans = self._getMoveMade()
		card = self.hand.getCard(int(ans))
		return card.suite
		
	def _playGame(self):
		for i in range(0, 5):		#recieve first 5 cards
			resp = self.sock.recv(2)
			self.hand.addCard(cards.str2Card(resp))
		self.hand.sortHand()
		#print self.hand
		self.qOut.put(self._getHand())		
		resp = self.sock.recv(1)		#asks for selecting rung, or tells the rung
		#print resp
		if(resp == "s"):		#handle if asked for selecting rung
			self.qStatus.put("sSelect Rung")
			rung = self._getRung()
			self.sock.send(rung)
			resp = self.sock.recv(1)	#in case of player who selected the rung, rung is echoed
			self.qStatus.put("r" + resp)
			#print resp
		else:
			self.qStatus.put("r" + resp)		#handle if told rung
			print resp
		for i in range(0, 8):		#recieve 8 more cards
			resp = self.sock.recv(2)
			self.hand.addCard(cards.str2Card(resp))
		
		self.hand.sortHand()
		print self.hand
		self.qOut.put(self._getHand())
		i = 0
		while(i < 13):
			j = 0
			msg = self.sock.recv(5)	#team score at the start of each move
			self.qStatus.put("t" + msg)
			self.qMove.put("n")
			self.moveColor = "n"
			while(j < 4):
				msg = self.sock.recv(11)	#tells who to move
				self.qStatus.put("s" + msg)
				#print msg
				if(msg[0] == "y"):		#handle if its your move
					card = self._getMove(self.moveColor)
					self.sock.send(card.toString())
					i += 1
				else:			#handle if its someone else's move
					pass
				msg = self.sock.recv(3)		#gets the last move made by any player
				#print "recieved moved: " + msg
				if(self.moveColor == "n"):
					self.moveColor = msg[2]
				self.qMove.put(msg)				
				j += 1
		msg = self.sock.recv(1)		#tells who won the game
		self.qOut.put("r")
		self.qStatus.put("d"+msg)
		self._wait4OK()
		print("game winner is team: " + msg)
		
	def _wait4OK(self):
		print("waiting for ok singnal")
		while(True):
			if(self.qIn.qsize()):
				msg = self.qIn.get(0)
				if(msg == "ok"):
					self.sock.send("ok")
					print("got the ok signal")
					return
				else:
					print("never should have come here")

		
	def _printHand(self):
		for i in range(0, self.hand.size()):
			print(str(i) + ")"),
			self.hand.getCard(i).printCard()
		
	def _getMoveMade(self):
		self.qOut.put("i")
		while(True):
			if(self.qIn.qsize()):
				msg = self.qIn.get(0)
				return msg
			else:
				time.sleep(.5)
	
	def _getSeat(self, seats):
		self.qStatus.put("c"+seats)
		while(True):
			if(self.qIn.qsize()):
				msg = self.qIn.get(0)
				return msg
			else:
				time.sleep(.5)
		
			
	def _getMove(self, moveColor):
		ans = self._getMoveMade()
		card = self.hand.getCard(int(ans))
		if(moveColor == "n"):
			retcard = self.hand.removeCard(int(ans))
			self.qOut.put(self._getHand())
			return retcard
		while(card.suite != moveColor):
			if(self.hand.checkColor(moveColor)):
				print("you still have a card of the suite being played!")
				ans = self._getMoveMade()
				card = self.hand.getCard(int(ans))
			else:
				break
		retcard = self.hand.removeCard(int(ans))
		self.qOut.put(self._getHand())
		return retcard
			
	def _getMoveColor(self, msg):
		rnd = msg.split(":")[1].split(";")
		if(rnd[0] != ''):
			print rnd
			moveColor = rnd[0][1]
			return moveColor
		else:
			return "n"

if(__name__ == '__main__'):
	if(len(sys.argv) < 2):
		print("usage: python client.py [username]")
	elif(len(sys.argv[1]) != 3):
		print("username should be 3 letters") 
	else:
		name = sys.argv[1]
		c = Client(name)
		#c.connect(_HOST, _PORT)

